package fr.miage.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import fr.miage.connexion.ConnexionBD;
import fr.miage.model.Adress;

public class AdressDAO {
	
	private Logger logger = Logger.getRootLogger();

	public Adress getById(String idAdress) {
		ResultSet res = null;
		String query = "select * from adress WHERE idAdress="+idAdress;
		Statement st = null;
		Adress adress = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			if(res.next()){
				adress = getAdress(res);
			}else{
				return null;
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return adress;
	}

	private Adress getAdress(ResultSet res) {
		Adress adress = new Adress();
		try {
			adress.setIdAdress(res.getLong("idAdress"));
			adress.setPlace(res.getString("place"));
			adress.setLocation(res.getString("location"));
			adress.setLatitude(res.getLong("latitude"));
			adress.setLongitude(res.getLong("longitude"));
		} catch (SQLException e) {
			logger.error(e);
		}
		return adress;
	}

	public Adress getAdressByUser(String idUser) {
		ResultSet res = null;
		String query = "select * from adress a inner join user u on a.idAdress = u.idAdress WHERE u.idUser="+idUser;
		Statement st = null;
		Adress adress = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			if(res.next()){
				adress = getAdress(res);
			}else{
				return null;
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return adress;
	}

}
